package com.shhimto.member.client.ui;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.shhimto.member.client.model.MemberPersonal;
import com.shhimto.member.client.service.MemberCallBack;
import com.shhimto.member.client.service.MemberService;
import com.shhimto.member.client.service.MemberServiceAsync;

public class AddMember extends Composite {

	private static AddMemberUiBinder uiBinder = GWT.create(AddMemberUiBinder.class);
	interface AddMemberUiBinder extends UiBinder<Widget, AddMember> {}
	private Widget addMember ;
	private DatePicker birthDatePicker ;
	private PopupPanel birthDatePopup ;
	@UiField TextBox birthDate ;
	@UiField TextBox nameField ;
	@UiField HorizontalPanel birthDatePanel ;
	@UiField Button addMemberButton;
	
	public AddMember() {
		addMember = uiBinder.createAndBindUi(this);
		birthDatePopup = new PopupPanel() ;
		birthDatePicker = new DatePicker() ;
		birthDatePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {

			@Override
			public void onValueChange(ValueChangeEvent<Date> event) {
				Date date = event.getValue() ;
				String dateString = DateTimeFormat.getFormat("dd/MM/yyyy").format(date) ;
				birthDate.setText(dateString);
				birthDatePopup.hide();
				birthDate.setEnabled(true);
				
			}
		}) ;
		
	}
	
	public Widget getAddMember(){
		return addMember ;
	}
	
	@UiHandler("birthDate")
	void onClickBirthDate(ClickEvent clickEvent){
		birthDatePopup.add(birthDatePicker);
		birthDatePopup.showRelativeTo(birthDate);
		birthDate.setEnabled(false);
	}
	
	@UiHandler("addMemberButton")
	void onClickAddMember(ClickEvent clickEvent){
		MemberPersonal memberPersonal = new MemberPersonal() ;
		memberPersonal.setName(nameField.getText());
		
		MemberServiceAsync service =(MemberServiceAsync)GWT.create(MemberService.class) ;
		ServiceDefTarget serviceDef = (ServiceDefTarget) service ;
		serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL() + "member");
		MemberCallBack memberCallBack = new MemberCallBack() ;
		service.addMember(memberPersonal, memberCallBack);
				
		
	
	}
}
